package com.coffee.middleware.dict.repository;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coffee.core.CoffeeException;
import com.coffee.core.CoffeeResponseEnum;
import com.coffee.middleware.dict.entity.DictTypeEntity;
import com.coffee.middleware.dict.entity.DictTypeVO;
import com.coffee.middleware.dict.repository.mapper.DictTypeMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: songkui
 * @since: 2023/5/12 11:40
 */
@Service
public class DictTypeRepository extends ServiceImpl<DictTypeMapper, DictTypeEntity> {


    public Integer saveDict(DictTypeEntity entity){
        Assert.notNull(entity, "entity is null");
        if (checkExist(entity, false)){
            throw new CoffeeException(CoffeeResponseEnum.DataExist);
        }
        this.save(entity);
        return entity.getId();
    }


    public void updateDict(DictTypeEntity entity){
        Assert.notNull(entity, "entity is null");
        if (checkExist(entity, true)){
            throw new CoffeeException(CoffeeResponseEnum.DataExist);
        }
        this.updateById(entity);
    }

    public List<DictTypeVO> listDictTypeVO(){
        List<DictTypeEntity> list = this.list();
        if (CollectionUtil.isEmpty(list)){
            return null;
        }
        return list.stream().map(DictTypeEntity::buildDictTypeVO).collect(Collectors.toList());
    }


    /**
     * 检查是否存在
     * @param typeEntity
     * @param update
     * @return  true : exist
     */
    private boolean checkExist(DictTypeEntity typeEntity, boolean update){
        List<DictTypeEntity> list = this.list();
        if (CollectionUtil.isEmpty(list)){
            return false;
        }

        int count = 0;
        for (DictTypeEntity entity : list){
            if (entity.getTypeCode().equals(typeEntity.getTypeCode())){
                ++ count;
            }
        }
        return update ? count > 1 : count > 0;
    }


}
